// 后端服务内容
// 该js运行环境属于 Main process范围，可以在这里对数据库，文件，网络等进行操作
const { dialog } = require('electron');
const { ipcMain: ipc } = require('electron-better-ipc');
const mysqlClient = require('./db/MysqlClient');
const CONSTS = require('../consts');
const localStorage = require('../localStorage');
const { closeModal, getSystemInformation } = require('../utils');

// add new service

// -- getUserByName --
ipc.answerRenderer(CONSTS.GET_USER_BY_NAME, async (userName) => {
    let sql = "SELECT * FROM cloud_user WHERE user_name = ?";
    return new Promise((resolve, reject) => {
        mysqlClient.query(sql, userName, (err, result) => {
            if (err) {
                console.log(err);
                reject(err);
                return;
            }
            resolve(result);
        });
    });
});

// close modal window
ipc.answerRenderer(CONSTS.CLOSE_LAST_MODAL, async () => {
    closeModal();
});

// get system information
ipc.answerRenderer(CONSTS.GET_SYSTEM_INFO, async () => {
    return new Promise((resolve, reject) => {
        resolve(getSystemInformation());
    });
});

// get database connection information
ipc.answerRenderer(CONSTS.GET_DB_CONFIG, async () => {
    return new Promise((resolve, reject) => {
        resolve(localStorage.get(CONSTS.DB_CONFIG));
    });
});

ipc.answerRenderer(CONSTS.SHOW_ALERT, (msg) => {
    dialog.showMessageBox({
        type: 'info',
        title: '提示',
        message: msg,
        buttons: ['确定']
    });
});